﻿using System;
using System.IO;
using System.Reflection;

namespace Fishing.Core
{
    internal static class WindowsStartup
    {
        public static void SetStartupRegistry(bool setStartup = false)
        {
            var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);

            if (key is null)
            {
                return;
            }

            var assembly = Assembly.GetExecutingAssembly();

            if (setStartup)
            {
                try
                {
                    key.SetValue(assembly.GetName().Name, "\"" + Path.ChangeExtension(assembly.Location, ".exe") + "\"");
                }
                catch
                {

                }
            }
            else
            {
                try
                {
                    key.DeleteValue(assembly.GetName().Name!, false);
                }
                catch
                {

                }
            }

            key.Close();
        }

        public static string GetStartupRegistry()
        {
            var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);

            if (key is null)
            {
                return string.Empty;
            }

            var curAssembly = Assembly.GetExecutingAssembly();

            string result = null;
            try
            {
                result = (string)key.GetValue(curAssembly.GetName().Name);
            }
            catch
            {

            }
            finally
            {
                key.Close();
            }
            return result;
        }

        public static int CheckStartupRegistry()
        {
            int status;
            var startupKey = GetStartupRegistry();
            if (string.IsNullOrEmpty(startupKey))
            {
                status = 0;
            }
            else if (string.Equals(startupKey, "\"" + Path.ChangeExtension(Assembly.GetExecutingAssembly().Location, ".exe") + "\"", StringComparison.Ordinal))
            {
                status = 1;
            }
            else
            {
                status = -1;
            }
            return status;
        }
    }
}
